package com.webhook.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 知码学院：带你轻松学Java
 * www.it235.com
 * QQ：3020685261
 */
@RestController
@RequestMapping("webhook")
public class PullController {

    @Value("${shell.startFileName:start.sh}")
    private String startFileName;

    @Value("${shell.directory}")
    private String directory;

    @Value("${shell.token:zhima686}")
    private String token;

    private static final Logger logger = LoggerFactory.getLogger(PullController.class);

    /**
     * 请求
     * @param userAgent
     * @param giteeToken
     * @param giteeEvent
     * @return
     * @throws IOException
     */
    @PostMapping("it235")
    public String auto(@RequestHeader("User-Agent") String userAgent,
                       @RequestHeader("X-Gitee-Token") String giteeToken,
                       @RequestHeader("X-Gitee-Event") String giteeEvent) throws IOException {
        //git-oschina-hook
        logger.info("User-Agent:{}", userAgent);
        //zhimaxxx
        logger.info("X-Gitee-Token:{}", giteeToken);
        //Push Hook
        logger.info("Gitee-Event:{}", giteeEvent);

        if("git-oschina-hook".equals(userAgent)
                && "PUSH HOOK".equals(giteeEvent)
                && token.equals(giteeToken)){
            //才去调用shell脚本
            executeShell();
            return "ok";
        }
        return "非法调用";
    }


    /**
     * 执行脚本
     * @throws IOException
     */
    public void executeShell() throws IOException {
        String fullName = getFullName(startFileName);
        File file = new File(fullName);
        if(!file.exists()) {
            logger.error("file {} not existed!", fullName);
            return;
        }
        //赋予755权限并调用
        ProcessBuilder processBuilder = new ProcessBuilder("/bin/chmod", "755", fullName);
        processBuilder.directory(new File(directory));
        Process process = processBuilder.start();

        int runningStatus = 0;
        try {
            runningStatus = process.waitFor();
        } catch (InterruptedException e) {
            logger.error("shell", e);
        }

        if(runningStatus != 0) {
            logger.error("failed.");
        }else {
            logger.info("success.");
        }
    }

    /**
     * 文件调用全路径
     * @param fileName
     * @return
     */
    private String getFullName(String fileName) {
        return directory + File.separator + fileName;
    }
}
